using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.Security;
using System.Net;
using System.IO;


namespace SharepointJon.Twitter
{
    public class SharepointTwitterWebPart : WebPart
    {
        private TextBox txtUsername;
        private TextBox txtPassword;
        private TextBox txtUpdate;
        private Label lblMessages;
        private Label lblTwitterResults;
        private HyperLink lnkTinyUrl;
        LinkButton lnkLogin;

        UpdatePanel updatePanel;
        ScriptManager scriptManager;

        string user = "";
        string pass = "";

        Panel loginPanel;
        Panel mainPanel;


        protected override void CreateChildControls()
        {
            this.Title = "SharePoint Twitter";
            this.TitleUrl = @"http://www.codeplex.com/SharepointTwitter/";

            // Prepare panels
            loginPanel = new Panel();
            loginPanel.ID = "loginPanel";
            loginPanel.Visible = true;

            mainPanel = new Panel();
            mainPanel.ID = "mainPanel";
            mainPanel.Visible = false;


            // Prepare AJAX controls
            updatePanel = new UpdatePanel();
            scriptManager = new ScriptManager();

            #region [   Layout Page Controls   ]

            // --------------------------------------------------------------------------------------------
            // Layout the controls
            // --------------------------------------------------------------------------------------------
            Label lblUsername = new Label();
            lblUsername.Text = "<b>Username:</b>";
            lblUsername.ID = "lblUsername";

            Label lblPassword = new Label();
            lblPassword.Text = "<b>Password:</b>";
            lblPassword.ID = "lblPassword";

            txtUsername = new TextBox();
            txtUsername.ID = "txtUsername";
            txtUsername.Attributes.Add("width", "185px");
            txtUsername.TabIndex = 1;
            txtUsername.Style.Add("font-family", "Verdana");
            txtUsername.Style.Add("font-size", "8pt");

            txtPassword = new TextBox();
            txtPassword.TextMode = TextBoxMode.Password;
            txtPassword.ID = "txtPassword";
            txtPassword.Attributes.Add("width", "185px");
            txtPassword.TabIndex = 2;
            txtPassword.Style.Add("font-family", "Verdana");
            txtPassword.Style.Add("font-size", "8pt");

            txtUpdate = new TextBox();
            txtUpdate.ID = "txtUpdate";
            txtUpdate.TextMode = TextBoxMode.MultiLine;
            txtUpdate.Width = new Unit(248);
            txtUpdate.Rows = 4;
            txtUpdate.TabIndex = 3;
            txtUpdate.Style.Add("font-family", "Verdana");
            txtUpdate.Style.Add("font-size", "8pt");

            Button cmdSubmit = new Button();
            cmdSubmit.Text = "Submit";
            cmdSubmit.ID = "cmdSubmit";
            cmdSubmit.Click += new EventHandler(cmdSubmit_Click);
            cmdSubmit.TabIndex = 4;
            cmdSubmit.Style.Add("font-family", "Verdana");
            cmdSubmit.Style.Add("font-weight", "bold");

            lnkLogin = new LinkButton();
            lnkLogin.ID = "lnkLogin";
            lnkLogin.Text = "Log In";
            lnkLogin.Style.Add("font-family", "Verdana");
            lnkLogin.Style.Add("font-weight", "bold");
            lnkLogin.Click += new EventHandler(lnkLogin_Click);

            Label space = new Label();
            space.Text = "<br><br>";
            space.ID = "space";


            // --------------------------------------------------------------------------------------------
            // Prepare the table
            // --------------------------------------------------------------------------------------------
            Table tbl = new Table();

            // Username row
            TableRow tr = new TableRow();
            TableCell td = new TableCell();
            td.Attributes.Add("width", "90px");
            td.Controls.Add(lblUsername);
            tr.Cells.Add(td);

            td = new TableCell();
            td.Controls.Add(txtUsername);
            tr.Cells.Add(td);
            tbl.Rows.Add(tr);

            // Password row
            tr = new TableRow();
            td = new TableCell();
            td.Attributes.Add("width", "90px");
            td.Controls.Add(lblPassword);
            tr.Cells.Add(td);

            td = new TableCell();
            td.Controls.Add(txtPassword);
            tr.Cells.Add(td);
            tbl.Rows.Add(tr);

            // Add some space
            tr = new TableRow();
            td = new TableCell();
            td.ColumnSpan = 2;
            tr.Cells.Add(td);
            tr.Style.Add("height", "5px");
            tbl.Rows.Add(tr);

            // Login button
            tr = new TableRow();
            td = new TableCell();
            td.ColumnSpan = 2;
            td.Controls.Add(lnkLogin);
            tr.Cells.Add(td);
            tbl.Rows.Add(tr);


            Table tbl2 = new Table();
            
            // Show the update textbox
            tr = new TableRow();
            td = new TableCell();
            td.ColumnSpan = 2;

            td.Controls.Add(txtUpdate);
            tr.Cells.Add(td);
            tbl2.Rows.Add(tr);

            // Add some space
            tr = new TableRow();
            td = new TableCell();
            tr.Attributes.Add("height", "10px");
            tr.Cells.Add(td);
            tbl2.Rows.Add(tr);

            // Add button
            tr = new TableRow();
            td = new TableCell();
            td.Controls.Add(cmdSubmit);
            tr.Cells.Add(td);
            tbl2.Rows.Add(tr);

#endregion

            loginPanel.Controls.Add(tbl);
            mainPanel.Controls.Add(tbl2);

            bool weHaveCredentials = FetchCredentials();
            if (weHaveCredentials)
            {
                mainPanel.Visible = true;
                loginPanel.Visible = false;
            }
            else
            {
                mainPanel.Visible = false;
                loginPanel.Visible = true;
            }

            
            // Add controls to the AJAX UpdatePanel
            updatePanel.ContentTemplateContainer.Controls.Add(loginPanel);
            updatePanel.ContentTemplateContainer.Controls.Add(mainPanel);

            // Add the ScriptManager to the page first, then the UpdatePanel
            if (Page.Controls.Contains(scriptManager)) { Page.Controls.Remove(scriptManager); }
            Controls.Add(scriptManager);
            Controls.Add(updatePanel);

            if (loginPanel.Visible == true) { txtUsername.Focus(); }

        }

        protected void lnkLogin_Click(object sender, EventArgs e)
        {
            SetCookie();
            CreateChildControls();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
        }

        protected void cmdSubmit_Click(object sender, EventArgs e)
        {
            TwitterWrapper twitter = new TwitterWrapper();
            string response = twitter.Update(user, pass, txtUpdate.Text, TwitterWrapper.OutputFormatType.XML);

            lblTwitterResults = new Label();
            lblTwitterResults.Text = "<br><br><b>Successfully updated your status on Twitter!</b><br><br>" + response;
            Controls.Add(lblTwitterResults);

            string tinyUrl = HelperMethods.GetTinyUrl("http://www.msnbc.msn.com/");
            lblMessages = new Label();
            lblMessages.Text = "<br><br>TinyURL = ";
            updatePanel.ContentTemplateContainer.Controls.Add(lblMessages);

            lnkTinyUrl = new HyperLink();
            lnkTinyUrl.Text = tinyUrl;
            lnkTinyUrl.NavigateUrl = tinyUrl;
            lnkTinyUrl.Target = "_blank";
            updatePanel.ContentTemplateContainer.Controls.Add(lnkTinyUrl);

        }

        private void SetCookie()
        {
            string encryptedPassword = HelperMethods.Encrypt(txtPassword.Text, true);
            HttpCookie userCookie = new HttpCookie("SharePointTwitterUser", txtUsername.Text);
            HttpCookie passCookie = new HttpCookie("SharePointTwitterPass", encryptedPassword);

            Page.Response.Cookies.Add(userCookie);
            Page.Response.Cookies.Add(passCookie);
            
        }

        private bool FetchCredentials()
        {
            // Try to fetch login from cookie
            try
            {
                HttpCookie userCookie = Page.Request.Cookies["SharePointTwitterUser"];
                HttpCookie passCookie = Page.Request.Cookies["SharePointTwitterPass"];

                user = userCookie.Value;
                pass = passCookie.Value;
                pass = HelperMethods.Decrypt(pass, true);

                return true;

            }
            catch
            {
                user = "";
                pass = "";
                return false;
            }

        }


    }
}
